package com.example.starter.redisson.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.example.starter.redisson.constant.LockMode;
import org.redisson.api.RLock;

import java.util.Optional;

/**
 * @author 王令
 * @since 2022/11/23 14:39
 */
public class LockModeElectionStrategyFactory {

    /**
     * 选举策略
     */
    public static LockModeStrategy election(LockMode mode) {
        return SpringUtil.getBeansOfType(LockModeStrategy.class).values().stream().filter(strategy -> strategy.elected(mode)).findFirst().orElse(null);
    }

    /**
     * 选举策略 获取RLock
     */
    public static RLock election(LockMode mode, String key) {
        return Optional.ofNullable(election(mode)).map(strategy -> strategy.getLock(key)).orElse(null);
    }
}
